//
//  LFHomeView.m
//  College
//
//  Created by LF on 2018/11/7.
//  Copyright © 2018 MuXi. All rights reserved.
//

#import "LFHomeView.h"
#import "LFFoodTableViewCell.h"

static NSString *foodCell = @"foodCell";

@interface LFHomeView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView; /**< tb */
@property (nonatomic, strong) UIButton *addBtn; /**< 添加 */
@property (nonatomic, strong) LFHomeVM *viewModel; /**< vm */
@property (nonatomic, strong) LFNavigationBar *nav; /**< na */
@end

@implementation LFHomeView

- (instancetype)initWithViewModel:(id)viewModel {
    self.viewModel = viewModel;
    return [super initWithViewModel:viewModel];
}

- (void)updateConstraints {
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.nav.mas_bottom);
        make.left.right.bottom.equalTo(self);
    }];
    [self.addBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(self).with.offset(-20);
        make.width.height.mas_equalTo(50);
    }];
    [self.nav mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.height.mas_equalTo(navHeight);
    }];
    
    [super updateConstraints];
}

- (void)lf_bindViewModel {
    @weakify(self)
    [self.viewModel.refreshUISubject subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self.tableView reloadData];
    }];
    [self.viewModel.getList.executionSignals.switchToLatest subscribeNext:^(id  _Nullable x) {
        @strongify(self)
        [self.tableView reloadData];
        [self.tableView.mj_header endRefreshing];
        if ([x boolValue] == YES) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        } else {
            [self.tableView.mj_footer endRefreshing];
        }
    } error:^(NSError * _Nullable error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)lf_setupViews {
    [self addSubview:self.tableView];
    [self addSubview:self.addBtn];
    [self addSubview:self.nav];
    
    [self updateConstraintsIfNeeded];
    [self setNeedsUpdateConstraints];
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerNib:[UINib nibWithNibName:@"LFFoodTableViewCell" bundle:nil] forCellReuseIdentifier:foodCell];
        @weakify(self)
        _tableView.mj_header = [LFRefreshHeader headerWithRefreshingBlock:^{
           @strongify(self)
            self.viewModel.net.type = RefreshTypeDown;
            [self.viewModel.getList execute:nil];
        }];
        _tableView.mj_footer = [LFRefreshAutoStateFooter footerWithRefreshingBlock:^{
            @strongify(self)
            self.viewModel.net.type = RefreshTypeUp;
            [self.viewModel.getList execute:nil];
        }];
        [_tableView.mj_header beginRefreshing];
    }
    return _tableView;
}

- (LFNavigationBar *)nav {
    if (!_nav) {
        @weakify(self)
        _nav = [[LFNavigationBar alloc] initWithTitle:@"首页" rightTitle:@"开始" rightAction:^{
            @strongify(self)
            [self timer];
        }];
        _nav.leftTitle = @"";
//        _nav.rightButtonLength = 120;
//        _nav.marginRight = 30;
//        _nav = [[LFNavigationBar alloc] init];
//        _nav.rightImageName = @"tab_img_home_selected";
//        _nav.title = @"jdaioad";
    }
    return _nav;
}

- (void) timer {
    if ([self.nav.rightTitle isEqualToString:@"开始"]) {
        self.nav.rightTitle = @"停止";
        [self.viewModel.timer setFireDate:[NSDate distantPast]];
    } else {
        self.nav.rightTitle = @"开始";
        [self.viewModel.timer setFireDate:[NSDate distantFuture]];
    }
}

- (UIButton *)addBtn {
    if (!_addBtn) {
        _addBtn = [LFBaseButton buttonWithType:UIButtonTypeContactAdd];
        _addBtn.backgroundColor = UIColor.lightTextColor;
        @weakify(self)
        [[_addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            @strongify(self)
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"提示"
                                                                           message:@"" preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                                                                 //响应事件
                                                                 //得到文本信息
                                                                 for(UITextField *text in alert.textFields){
                                                                     [self.viewModel.addFood execute:text.text];
                                                                 }
                                                             }];
            UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
                textField.placeholder = @"请输入";
            }];
            [alert addAction:okAction];
            [alert addAction:cancelAction];
            [CURRENT_NAV.topViewController presentViewController:alert animated:YES completion:nil];
        }];
    }
    return _addBtn;
}

#pragma mark - tb
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    tableView.mj_footer.hidden = self.viewModel.datas.count == 0;
    return self.viewModel.datas.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LFFoodTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:foodCell];
    
    cell.food = self.viewModel.datas[indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    LFBaseViewController *vc = [LFBaseViewController new];
    vc.view.backgroundColor = UIColor.brownColor;
    [CURRENT_NAV pushViewController:vc animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 46;
}

@end
